// WARN doesn't handle documentElement replaced
ext.define('ext', function() {

var messages = extension.messages;
var utils = extension.utils;
var model = extension.model;
var view = extension.view;

function freeupScreenSpace() {
    view.unlockSidebar();
    view.closeDialog();
}

function onTagRemove(offset) {
    model.remove({offset: offset});
}

function onTagEdit(offset) {
    var tag = model.get(offset);
    view.lockSidebar();
    view.openDialog({
        title: 'Edit tag',
        text: tag.text,
        color: tag.color,
        callback: function(event, info) {
            if (event !== 'cancel') {
                tag.update(info);
                model.set(tag);
            }
            freeupScreenSpace();
        }
    });
}

function onPageScroll(offset) {
    var tag = model.get(offset);
    if (tag.box != null) {
        view.highlightPage({
            color: utils.mapColor(tag.color),
            coords: tag.box
        });
    }
}

var API = {
    showDialog: function() {
        view.openDialog({
            title: 'Create tag',
            text: '',
            color: utils.randomColor(),
            callback: function(event, info) {
                if (event === 'cancel') {
                    freeupScreenSpace();
                    return;
                }

                var tag = model.get(window.pageYOffset);
                tag.update(info);
                model.set(tag);

                if (event === 'save')
                    freeupScreenSpace();

                if (event === 'highlight')
                    view.openDialog();
            }
        });
    },
    saveTag: function(str) {
        var tag = model.get(window.pageYOffset);
        tag.update({
            text: str,
            color: utils.randomColor()
        });
        model.set(tag);
    },
    clearTags: function() {
        model.clear();
    },
    toggleTags: function() {
        view.toggleSidebar();
    },
    showHighlighter: function() {
        var tag = model.get(window.pageYOffset);
        var color = tag.color || utils.randomColor();
        view.showHighlighter({
            color: color,
            callback: function(rectangle) {
                tag.update({
                    offset: window.pageYOffset,
                    color: color,
                    box: rectangle
                });
                model.set(tag);
            }
        });
    }
};

return {
    initialize: function() {
        if (window.Webtags != null) {
            window.Webtags = API;
            model.bind();
            view.bind();
            messages.listen({
                'view-sidebar-remove': onTagRemove,
                'view-sidebar-edit': onTagEdit,
                'view-page-scrolled': onPageScroll
            });
            messages.send('extension-ready');
        }
    }
};

});

ext.initialize();
